using System.ComponentModel;
using System.Runtime.CompilerServices;
using Avalonia.Threading;

namespace JMCOM.Components.EpsonRobot.NodeFlow.Nodebehind;

public class TransitionViewModel : BindableBase
{
    private StateNodeViewModel _source = default!;
    public StateNodeViewModel Source
    {
        get => _source;
        set => SetProperty(ref _source, value);
    }

    private StateNodeViewModel _target = default!;
    public StateNodeViewModel Target
    {
        get => _target;
        set => SetProperty(ref _target, value);
    }

    private BlackboardItemReferenceViewModel? _conditionReference;
    public BlackboardItemReferenceViewModel? ConditionReference
    {
        get => _conditionReference;
        set
        {
            if (SetProperty(ref _conditionReference, value))
            {
                SetCondition(_conditionReference);
            }
        }
    }

    public BlackboardItemViewModel? Condition { get; private set; }

    private bool _isActive;
    public bool IsActive
    {
        get => _isActive;
        set => SetProperty(ref _isActive, value);
    }

    private void SetCondition(BlackboardItemReferenceViewModel? conditionRef)
    {
        Condition = BlackboardDescriptor.GetItem(conditionRef);

        OnPropertyChanged(nameof(Condition));
    }
    public virtual Action<Action> PropertyChangedDispatcher { get; set; } = Dispatcher.UIThread.Invoke;

    /// <summary>
    /// Occurs when a property value changes
    /// </summary>
    public event PropertyChangedEventHandler? PropertyChanged;

    /// <summary>
    /// Fires the PropertyChanged notification.
    /// </summary>
    /// <remarks>Specially named so that Fody.PropertyChanged calls it</remarks>
    /// <param name="propertyName">Name of the property to raise the notification for</param>
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChangedDispatcher(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)));
    }
}